<template>
  <div class="innerContainer">
    <common-title :text="`文件详情 （ ${searchForm.fileName} ）`">
      <template #expand>
        <el-button type="primary" plain size="mini" @click="router.go(-1)">返回上一级</el-button>
      </template>
    </common-title>

    <div class="innerPane">

      <div class="container">
        <el-scrollbar>
          <div class="lineChart" v-for="item in chartData" :id="'line' + item" :key="item">
          </div>
        </el-scrollbar>
      </div>
    </div>
  </div>


</template>

<script setup>

import CommonTitle from "@/components/CommonTitle.vue";

import { onMounted, onUnmounted, ref, nextTick, computed } from "vue";

import { ElMessage } from "element-plus";


import { uploadSyncBuild, uploadSyncChannel, uploadSyncData } from "../../utils/requests";

import * as echarts from "echarts";

import { useRouter } from "vue-router";

import { storage } from '@/utils/storage.js';
import { de, el } from "element-plus/es/locales.mjs";

const router = useRouter();


const searchForm = ref({
  task: null,
  id: null,
  fileName: null
});


let chartData = ref([]);

let chartObj = ref();

onMounted(async () => {
  searchForm.value.task = router.currentRoute.value.query.task;

  searchForm.value.id = router.currentRoute.value.query.id;

  searchForm.value.fileName = router.currentRoute.value.query.fileName;

  window.addEventListener("resize", resize);


  handleLastData();
});

const resetData = () => {
  chartData.value = [];
  chartObj = {};
};

/**
 * 立即执行一次；只有返回 null/undefined/false 才继续轮询
 * @param {Number} delay        轮询间隔(ms)，默认 500
 * @param {Function} fn         返回 truthy 即成功；支持 async
 * @param {Number} maxDuration  最大持续时间(ms)，默认 20 秒
 * @param {Number} maxRetries   最大重试次数，默认 40 次
 * @returns {Promise<*>}        成功值 / 超时返回 null
 */
const requestWait = (
  delay = 500,
  fn,
  predicate
) =>
  new Promise((resolve) => {
    let running = false;

    const start = Date.now()

    const tick = async () => {
      if (running) return;       // 上一轮没跑完，本轮直接跳过
      running = true

      try {
        const res = await fn()   // 业务函数

        console.log('轮询结果：', res)

        if (predicate(res)) {  // 业务函数返回值符合要求
          return resolve(res)    // 成功
        }

        // if (res != null) {

        // }
      } finally {
        running = false          // 无论成功/异常都要解锁
      }


      // 超时：累计时间
      if (Date.now() - start >= 10000) {
        ElMessage.info('获取数据超时')
        return resolve(null)
      }

      setTimeout(tick, delay)
    }

    tick() // 立即执行第一次
  })



const handleLastData = async () => {
  resetData();

  uploadSyncChannel({task:searchForm.value.task}).then(res=>{
   chartData.value =  res;

   chartData.value.forEach(item=>{
        uploadSyncData({ task: searchForm.value.task, id: searchForm.value.id, channelNo: item }).then(data=>{
           chartObj["chart" + item] = {
              data: data
            };
            nextTick(()=>{
              chartObj["chart" + item ].ele = echarts.init(document.getElementById("line" +item ));
              setChart(chartObj["chart" + item ].ele, chartObj["chart" + item ].data);
            })
        })
      })
  })
 
};

const resize = () => {
  for (let key in chartObj) {
    if (chartObj[key].ele) {
      chartObj[key].ele.resize();
    }
  }
};


const setChart = (ele, data) => {

  var series = [
    {
      type: "line",
      large: true,
      progressive: 1000, // 分片渲染（每3000点渲染一次）
      clip: true,
      showSymbol: false,
      lineStyle: {
        width: 0.8,
        color: "#0089ff",
        opacity: 0.9, // 轻微透明提升渲染性能
        cap: "butt",
      }, // 直线端点样式（性能最优） },
      label: {
        show: false,
      },
      blendMode: "source-over", // 避免透明通道计算
      itemStyle: {
        color: "#0089ff",
      },
      data: data.data,
    },
  ];
  var options = {
    legend: {
      show: true,
      right: 0,
    },
    tooltip: {
      show: true,
      trigger: "axis",
    },
    title: [{
      text: data.label,
      textAlign: "center",
      left: 30,
      top: 10,
      textStyle: { fontSize: 16, fontWeight: 'bold' }
    }],
    grid: {
      left: "3%",
      right: 80,
      bottom: "5%",
      top: 50,
      containLabel: true,
    },
    dataZoom: [
      {
        type: "inside",
        throttle: 200, // 操作节流200ms
        realtime: false, // 关闭实时更新
        zoomLock: false,
        start: 0,
        end: 100,
      },
      {
        type: "slider",
        realtime: false, // 重要！必须关闭实时渲染
        brushSelect: false,
        throttle: 300,
        height: 15,
        bottom: 0,
      },
    ],
    animation: false,
    xAxis: [
      {
        type: "category",
        name: "时间（s）",
        nameGap: 8,
        splitLine: {
          show: false,
        },
        axisLine: {
          show: true,
          lineStyle: {
            width: 1,
            color: "#aaa",
          },
        },
        axisTick: {
          show: false,
        },
        data: data.time,
        axisLabel: {
          show: true,
          // rotate: 30,
          formatter: function (value) {

            return value.replace(/\s+/g, "\n");
          },
          textStyle: {
            color: "#666",
            fontSize: 14,
          },
        },
      },
    ],
    yAxis: [
      {
        type: "value",
        nameLocation: "end",
        splitLine: {
          show: true,
          lineStyle: {
            width: 1,
            color: "#ebebeb",
          },
        },
        axisLine: {
          show: false,
        },
        min: 'dataMin',
        max: 'dataMax',
        axisLabel: {
          textStyle: {
            color: "#666",
            fontSize: 14,
          },
        },
      },
    ],
    series: series,
  };
  ele.clear();
  ele.setOption(options, true);
  ele.hideLoading();
};

</script>

<style scoped lang="scss">
.container {
  /* 容器样式 */
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.lineChart {
  margin: 20px 0;
  width: 100%;
  height: 320px;
}
</style>
